package org.example.project.toolkit;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import jakarta.servlet.http.HttpServletRequest;

import java.net.URI;
import java.util.Date;
import java.util.Optional;

import static org.example.project.common.constant.ShortLinkConstant.DEFAULT_VALIDATE_TIME;

/**
 * 短链接工具类
 *
 * @author weibin
 * @since 2025/10/12 21:35
 */
public class ShortLinkUtil {

    /**
     * 获取短链接有效时间
     *
     * @param date  时间
     * @return  有效期
     */
    public static long getValidaTime(Date date) {
        return Optional.ofNullable(date)
                .map(x -> DateUtil.between(x, new Date(), DateUnit.SECOND))
                .orElse(DEFAULT_VALIDATE_TIME);
    }

    /**
     * 根据请求获取用户真实访问 ip
     *
     * @param request   请求
     * @return  用户真实访问 IP地址
     */
    public static String getClientIp(HttpServletRequest request) {
        // 常见代理服务器设置的IP头（按优先级排序）
        String[] headers = {
                "X-Forwarded-For",
                "Proxy-Client-IP",
                "WL-Proxy-Client-IP",
                "HTTP_CLIENT_IP",
                "HTTP_X_FORWARDED_FOR"
        };

        // 遍历所有可能的头信息
        for (String header : headers) {
            String ip = request.getHeader(header);
            if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
                // 处理多级代理的情况：取第一个有效IP
                if (ip.contains(",")) {
                    ip = ip.split(",")[0];
                }
                return ip;
            }
        }

        // 直接获取远端地址（无代理时）
        return request.getRemoteAddr();
    }

    /**
     * 获取请求来源所属操作系统
     *
     * @param request   请求
     * @return  操作系统名称
     */
    public static String getOperatingSystem(HttpServletRequest request) {
        String userAgentStr = request.getHeader("User-Agent");
        if (userAgentStr == null || userAgentStr.isEmpty()) {
            return "未知";
        }

        UserAgent userAgent = UserAgentUtil.parse(userAgentStr);
        String fullOsName = userAgent.getOs().getName();

        if (fullOsName == null) {
            return "未知";
        }

        // 转换为小写方便匹配
        String lowerOsName = fullOsName.toLowerCase();

        if (lowerOsName.contains("windows")) {
            return "Windows";
        } else if (lowerOsName.contains("mac") || lowerOsName.contains("os x")) {
            return "macOS";
        } else if (lowerOsName.contains("linux")) {
            return "Linux";
        } else if (lowerOsName.contains("android")) {
            return "Android";
        } else if (lowerOsName.contains("ios") || lowerOsName.contains("iphone")) {
            return "iOS";
        } else if (lowerOsName.contains("ubuntu")) {
            return "Ubuntu";
        } else if (lowerOsName.contains("centos")) {
            return "CentOS";
        } else if (lowerOsName.contains("debian")) {
            return "Debian";
        } else if (lowerOsName.contains("fedora")) {
            return "Fedora";
        } else {
            // 无法识别的系统返回原始名称（或自定义处理）
            return fullOsName;
        }
    }

    /**
     * 获取请求来源所属浏览器
     *
     * @param request   请求
     * @return  浏览器名称
     */
    public static String getBrowser(HttpServletRequest request) {
        String userAgentStr = request.getHeader("User-Agent");
        if (userAgentStr == null || userAgentStr.isEmpty()) {
            return "未知";
        }

        UserAgent userAgent = UserAgentUtil.parse(userAgentStr);
        return userAgent.getBrowser().getName();
    }

    /**
     * 获取用户访问设备
     *
     * @param request 请求
     * @return 访问设备
     */
    public static String getDevice(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent.toLowerCase().contains("mobile")) {
            return "Mobile";
        }
        return "PC";
    }

    /**
     * 获取用户访问网络
     *
     * @param request 请求
     * @return 访问设备
     */
    public static String getNetwork(HttpServletRequest request) {
        String actualIp = getClientIp(request);
        // 这里简单判断IP地址范围，您可能需要更复杂的逻辑
        // 例如，通过调用IP地址库或调用第三方服务来判断网络类型
        return actualIp.startsWith("192.168.") || actualIp.startsWith("10.") ? "WIFI" : "Mobile";
    }


    /**
     * 获取链接的域名
     *
     * @param url 链接
     * @return  域名
     */
    public static String extractDomain(String url) {
        String domain = null;
        try {
            URI uri = new URI(url);
            String host = uri.getHost();
            if (StrUtil.isNotBlank(host)) {
                domain = host;
                if (domain.startsWith("www.")) {
                    domain = host.substring(4);
                }
            }
        } catch (Exception ignored) {
        }
        return domain;
    }
}
